package com.lagou.edu.service.impl;


import com.lagou.edu.dao.CodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务实现
 * 用于向指定邮箱，发送验证码
 */
@Slf4j
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeDao codeDao;
    @Lazy
    @Autowired
    private MailServiceFeign mailService;
    @Lazy
    @Autowired
    private UserServiceFeign userService;

    @Override
    public boolean createAndSend(String email) {
        boolean isRegistered = userService.isRegistered(email);
        if(isRegistered) {
            log.info("邮箱: {} 已经被使用了", email);
            return false;
        }
        //生成6位随机数字验证码
        String code = RandomStringUtils.random(6,false, true);
        System.out.println(String.format("向邮箱: %s 发送验证码: %s", email, code));
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(new Date());
        authCode.setExpiretime(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10))); //10分钟有效
        codeDao.save(authCode);

        mailService.sendMail(email, code);
        return true;
    }

    /**
     * 校验验证码是否正确，0正确 1错误 2超时
     * @param email
     * @param code
     * @return
     */
    @Override
    public int validate(String email, String code) {
        AuthCode authCode = codeDao.findByEmailAndCode(email, code);
        if(authCode == null) {
            return 1; //错误
        }
        Date now = new Date();
        if(now.after(authCode.getExpiretime())) { //超时
            return 2;
        }
        return 0; //正确
    }
}
